//
//  ClubTableViewController.swift
//  YueJian
//
//  Created by mac on 2017/10/19.
//  Copyright © 2017年 MapleStory. All rights reserved.
//

import UIKit
import Alamofire

class ClubTableViewController: UITableViewController {

    var array:[AnyObject]?
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "俱乐部"
        loadClub(type: 0)
        self.tableView.register(ClubTableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
    }
    
    
    func loadClub(type:Int) {

        let sessionId = UserDefaults.standard.value(forKey: "sessionId")
        
        if type == 0 {
            let params = ["SessionID":sessionId ?? "","mod":"club","page":1] as [String : Any]
            
            Alamofire.request(URL(string:"http://172.24.10.175/workout/api.php/lists/mod/club")!, method: HTTPMethod.post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
                print(response)
                self.array = response.result.value as! [AnyObject]
                
                self.tableView?.reloadData()
            }
            
        } else {
            let params = ["SessionID":sessionId, "longitude":159,"latitude":168]
            Alamofire.request(URL(string: Location_Club)!, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
                self.array = response.result.value as! [AnyObject]
                self.tableView.reloadData()
            }
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return array?.count ?? 0
    }

    @objc func segmenClick(segment:UISegmentedControl) {
        print(segment.selectedSegmentIndex)
        self.loadClub(type: segment.selectedSegmentIndex)
        
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! ClubTableViewCell
            cell.segment?.addTarget(self, action: #selector(segmenClick(segment:)), for: UIControlEvents.valueChanged)
            cell.selectionStyle = .none
            return cell
        } else {
            let cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")

            cell.backgroundView = UIImageView(image: UIImage(named: "scroller3"))
            cell.textLabel?.text = "瑜伽瑜伽"
            if array?.count != 0 {
                let dic = array?[indexPath.row] as! NSDictionary
                
                let str = dic["thumb"] as! String
                
                let imageStr = "http://172.24.10.175/workout/Uploads/"+str
                
                let images = try! UIImage(data: Data(contentsOf: URL(string: imageStr)!))
                
                cell.backgroundView = UIImageView(image: images)
                cell.textLabel?.text = dic["club_name"] as? String
            }
            
//            cell.detailTextLabel?.text = "瑜伽瑜伽"
            

            return cell
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = ClubDetailViewController()
        let dic = array?[indexPath.row] as! NSDictionary
        
        let id = dic["id"] as! String
        
        vc.id = id
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 50
        } else {
            return 180
        }
    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
